<?php

class Activity_Api_Like
{

	/**
	 * @return bool
	 */
	function isLiked($resource, $poster)
	{
		if (!$poster or !$resource)
		{
			return FALSE;
		}

		$table = Nuo::getTable('activity/like');

		$select = $table -> select();

		$select -> where('resource_id=?', $resource -> getItemId());

		$select -> where('poster_id=?', $poster -> getItemId());

		return $table -> fetchRow($select);
	}

	/**
	 * @param Database_Model_Item $resource
	 * @param int $userId
	 * @return TRUE/FALSE
	 */
	function toggleLike($resource, $poster)
	{
		$table = Nuo::getTable('activity/like');

		$select = $table -> select();
		
		$select -> where('resource_id=?', $resource -> getItemId());
		
		$select -> where('poster_id=?', $poster -> getItemId());

		$obj = $table -> fetchRow($select);

		if ($obj)
		{
			$obj -> delete();

			if (isset($resource -> like_count))
			{
				$resource -> like_count = $resource -> like_count - 1;
				$resource -> save();
			}
			return 0;
		}

		$obj = $table -> fetchNew();
		
		$obj -> resource_id = $resource -> getItemId();
		
		$obj -> poster_id = $poster -> getItemId();
		
		$obj -> created_at = time();
		
		$obj -> save();

		if (isset($resource -> like_count))
		{
			$resource -> like_count = $resource -> like_count + 1;
			$resource -> save();
		}
		return TRUE;
	}

}
